import Vue from "vue";
import VueI18n from "vue-i18n";
import forEach from "lodash/forEach";
import config from "common/config";

const languageFilesMap = require.context("../locales/", true, /\.js$/);

Vue.use(VueI18n);

// 获取 common/config.js 中支持的语言配置信息
const languageConfig = config.locale;

let i18nMessages = {};

Object.keys(languageConfig).forEach(language => {
  i18nMessages[language] = {};
});

const getLanguageMap = _ => {
  // ["./cn/index.js", "./cn/modules/config.js", "./en/index.js", "./en/modules/config.js"]
  // 第一步  将
  forEach(languageFilesMap.keys(), key => {
    let languageFileDefault = languageFilesMap(key).default;
    // 第一步： 去除 ./ 和 .js
    key = key.substr(2).slice(0, -3);
    //
    let filePathArray = key.split("/");

    // 当前语言
    let language = filePathArray[0];
    // 过滤掉配置中不支持的语言
    if (!i18nMessages[language]) {
      return true;
    }
    let processFilePathObj = i18nMessages[language];
    forEach(filePathArray.slice(1), filePath => {
      // 处理 index 文件 --不作为下一级路径
      if (filePath === "index") {
        return true;
      }
      if (processFilePathObj[filePath]) {
        processFilePathObj = processFilePathObj[filePath];
      } else {
        processFilePathObj[filePath] = {};
        processFilePathObj = processFilePathObj[filePath];
      }
    });

    Object.keys(languageFileDefault).forEach(key => {
      processFilePathObj[key] = languageFileDefault[key];
    });
  });

  return i18nMessages;
};

export default ({ app, store }) => {
  // Set i18n instance on app
  // This way we can use it in middleware and pages asyncData/fetch
  app.i18n = new VueI18n({
    locale: store.state.locale,
    fallbackLocale: "zh",
    messages: getLanguageMap()
  });

  app.i18n.path = link => {
    if (app.i18n.locale === app.i18n.fallbackLocale) {
      return `/${link}`;
    }

    return `/${app.i18n.locale}/${link}`;
  };
};
